import React from "react";
import { findDOMNode } from "react-dom";
import { Toast, Carousel, Modal, ActionSheet } from "antd-mobile";
import ReactPullLoad, { STATS } from "react-pullload";
import "../../../../node_modules/react-pullload/dist/ReactPullLoad.css";
import BenzAMRRecorder from "benz-amr-recorder";
import wx from "weixin-js-sdk";

const prompt = Modal.prompt;
var amr = new BenzAMRRecorder();

export default class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      imglist: [],
      slideIndex: 1,
      show: false,
      hasMore: true,
      data: [],
      action: STATS.init,
      page: 1,
      which_status: 0,
    };
  }
  componentDidMount() {
    document.title = "广场";
    this.getList();

    global.Ajax.hhtc_request("user/get_qrcode", {}).then((data) => {
      console.log("第一步 ", data);
      if (data.code === 1) {
        this.setState(data.data);
      }
    });

    global.Ajax.hhtc_request("web/get_share", {
      windowurl: window.location.href,
    }).then((data) => {
      console.log("分享页面的数据 ", data);
      if (data.code === 1) {
        wx.config({
          debug: false,
          appId: data.data.appId,
          timestamp: data.data.timestamp,
          nonceStr: data.data.noncestr,
          signature: data.data.signature,
          jsApiList: [
            // 所有要调用的 API 都要加到这个列表中
            "updateTimelineShareData", //分享给好友
            "updateAppMessageShareData", //分享到朋友圈
          ],
        });

        wx.checkJsApi({
          jsApiList: ["updateTimelineShareData", "updateAppMessageShareData"], // 需要检测的JS接口列表，所有JS接口列表见附录2,
          success: function (res) {
            console.log("checkJsApi--", res);
            // 以键值对的形式返回，可用的api值true，不可用为false
            // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
          },
        });
        wx.error(function (res) {
          console.log(res);
          // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
        });

        wx.ready(() => {
          //配置好需要分享的几个配置，这里只是演示，实际开发中应该是动态的变量
          var shareData = {
            title: "好友邀请你加入艺看学院",
            desc: "你的好友正在邀请你加入艺看学院，快来看看吧",
            link: window.location.href.split("#")[0],
            imgUrl:
              "https://yksy.qianjitianxia.com/o_1eiao12gcfa6122j1eicun0pjl8.png", //传递给微信需传递完整的带url链接
            success: function () {
              global.Ajax.hhtc_request("user/share", {}).then((data) => {
                console.log("data: ", data);
                // return Toast.success(data.msg);
              });
            },
          };

          //调用各个接口并传入配置变量
          wx.updateTimelineShareData(shareData);
          wx.updateAppMessageShareData(shareData);
        });
      }
    });
  }

  dataList = [
    { url: "o_1eib053ql1fqumchv3d1k2h2409", title: "视频", type: 3 },
    { url: "o_1eib053qlra3qv3i8d149k1o4fa", title: "音频", type: 2 },
    { url: "o_1eib0hqagasr67g129814qi10k08", title: "图片", type: 1 },
  ].map((obj) => ({
    icon: (
      <img
        src={`https://yksy.qianjitianxia.com/${obj.url}.png`}
        alt={obj.title}
        style={{ width: 36 }}
        onClick={() => {
          this.props.history.push("/page/home/square/release/" + obj.type);
        }}
      />
    ),
    title: obj.title,
  }));
  showShareActionSheet = () => {
    ActionSheet.showShareActionSheetWithOptions(
      {
        options: this.dataList,
        // title: 'title',
        // message: 'I am description, description, description',
      },
      (buttonIndex) => {
        this.setState({
          clicked1:
            buttonIndex > -1 ? this.dataList[buttonIndex].title : "cancel",
        });
        // also support Promise
        return new Promise((resolve) => {
          // Toast.info('closed after 1000ms');
          setTimeout(resolve, 10);
        });
      }
    );
  };
  dataList2 = [
    { url: "o_1eib053ql1fqumchv3d1k2h2409", title: "视频", type: 3 },
    { url: "o_1eib053qlra3qv3i8d149k1o4fa", title: "音频", type: 2 },
    { url: "o_1eib0hqagasr67g129814qi10k08", title: "图片", type: 1 },
    { url: "o_1eib053ql1fqumchv3d1k2h2409", title: "参赛视频", type: 4 },
  ].map((obj) => ({
    icon: (
      <img
        src={`https://yksy.qianjitianxia.com/${obj.url}.png`}
        alt={obj.title}
        style={{ width: 36 }}
        onClick={() => {
          this.props.history.push("/page/home/square/release/" + obj.type);
        }}
      />
    ),
    title: obj.title,
  }));
  showShareActionSheet2 = () => {
    ActionSheet.showShareActionSheetWithOptions(
      {
        options: this.dataList2,
        // title: 'title',
        // message: 'I am description, description, description',
      },
      (buttonIndex) => {
        this.setState({
          clicked1:
            buttonIndex > -1 ? this.dataList2[buttonIndex].title : "cancel",
        });
        // also support Promise
        return new Promise((resolve) => {
          // Toast.info('closed after 1000ms');
          setTimeout(resolve, 10);
        });
      }
    );
  };

  getList() {
    var req = {
      page: 1,
      size: 21,
    };
    global.Ajax.hhtc_request("dynamic/tielist", req).then((data) => {
      console.log("ppp", data);
      if (data.code === 1) {
        var hasMore;
        if (data.data.length > 0) {
          this.state.page++;
          hasMore = true;
        } else {
          hasMore = false;
        }
        this.setState({
          data: data.data.data,
          hasMore: hasMore,
          page: this.state.page,
          which_status: data.data.which_status,
        });
      }
    });
  }
  // 获取商品
  handleAction = (action) => {
    console.info(action, this.state.action, action === this.state.action);
    //new action must do not equel to old action
    if (action === this.state.action) {
      return false;
    }
    if (action === STATS.refreshing) {
      //刷新
      this.handRefreshing();
    } else if (action === STATS.loading) {
      //加载更多
      this.handLoadMore();
    } else {
      //DO NOT modify below code
      this.setState({
        action: action,
      });
    }
  };
  handRefreshing = () => {
    if (STATS.refreshing === this.state.action) {
      return false;
    }
    var req = {
      page: 1,
      size: 12,
    };
    global.Ajax.hhtc_request("dynamic/tielist", req).then((data) => {
      if (data.code === 1) {
        var hasMore;
        if (data.data.length > 0) {
          this.state.page++;
          hasMore = true;
        } else {
          hasMore = false;
        }
        this.setState({
          data: data.data.data,
          hasMore: hasMore,
          action: STATS.refreshed,
          page: this.state.page,
        });
      }
    });
    this.setState({
      action: STATS.refreshing,
    });
  };
  handLoadMore = () => {
    if (STATS.loading === this.state.action) {
      return false;
    }
    //无更多内容则不执行后面逻辑
    if (!this.state.hasMore) {
      return;
    }
    var req = {
      page: this.state.page,
      size: 12,
    };
    global.Ajax.hhtc_request("dynamic/tielist", req).then((data) => {
      if (data.code === 1) {
        if (data.data.length > 0) {
          this.setState({
            data: this.state.data.concat(data.data.data),
            action: STATS.reset,
          });
        } else {
          this.setState({
            action: STATS.reset,
            hasMore: false,
          });
        }
      }
    });
    this.setState({
      action: STATS.loading,
    });
  };
  // 献花
  xh(id, is_self) {
    if (is_self === 1) {
      return Toast.fail("不能给自己打赏!", 1);
    }
    prompt(
      <p>
        <img
          alt=''
          src={require("../../imgs/999.png")}
          style={{ display: "block", width: "9.334vw", margin: "0 auto" }}
        />
      </p>,
      "",
      [
        {
          text: "取消",
          onPress: (value) =>
            new Promise((resolve) => {
              resolve();
            }),
        },
        {
          text: "打赏",
          onPress: (value) =>
            new Promise((resolve, reject) => {
              if (value * 1 + "" === "NaN") {
                return Toast.fail("只能输入数字噢!", 1);
              }
              if (value !== "") {
                global.Ajax.hhtc_request("dynamic/dashang", {
                  id: id,
                  num: value,
                }).then((data) => {
                  if (data.code === 1) {
                    Toast.success(data.msg, 1);
                    resolve();
                  } else {
                    Toast.fail(data.msg, 1);
                  }
                });
              } else {
                Toast.fail("请输入打赏数量");
              }
            }),
        },
      ],
      "default",
      null,
      ["请输入要打赏的水晶数量"]
    );
  }
  // 点赞
  zan(id, index) {
    global.Ajax.hhtc_request("dynamic/dianzan", { id: id }).then((data) => {
      console.log("data: ", data);
      if (data.code === 1) {
        Toast.success(data.msg, 1);
        var data = this.state.data;
        if (data[index].is_zan === 0) {
          data[index].is_zan = 1;
          data[index].zan_num++;
        } else {
          data[index].is_zan = 0;
          data[index].zan_num--;
        }
        this.setState({
          data: data,
        });
      } else {
        Toast.fail(data.msg, 1);
      }
    });
  }

  // 点击播放按钮
  playVoice(url) {
    amr = new BenzAMRRecorder();
    var iconFlag = !this.state.iconFlag; // 这个变量是控制播放与否的
    var that = this;
    amr.initWithUrl(url).then(function () {
      amr.play();
      that.setState({
        iconFlag: iconFlag,
      });
    });
    // 监听播放完成
    amr.onEnded(() => {
      this.setState({
        iconFlag: false,
      });
    });
  }
  paused() {
    var iconFlag = !this.state.iconFlag; // 这个变量是控制播放与否的
    amr.stop();
    this.setState({
      iconFlag: iconFlag,
    });
  }
  render() {
    return (
      <div className='' style={{ paddingBottom: 70 }}>
        <img
          alt=''
          src={require("../../imgs/top.png")}
          className='sq_top_img'
          onClick={() => {
            this.props.history.push("/page/home/square/sqlist");
          }}
        />
        <div className='go_take'>
          <img alt='' src={require("../../imgs/take.png")} className='take' />
          <p>发布动态</p>
          {this.state.which_status == 1 ? (
            <span onClick={this.showShareActionSheet2}>前往</span>
          ) : (
            <span onClick={this.showShareActionSheet}>前往</span>
          )}
          <img alt='' src={require("../../imgs/r2.png")} className='r2' />
        </div>
        <ReactPullLoad
          downEnough={100}
          action={this.state.action}
          handleAction={this.handleAction}
          hasMore={this.state.hasMore}
          distanceBottom={100}
        >
          <div className='sq_list'>
            {this.state.data.map((item, index) => {
              return (
                <div key={"list" + index} className='item'>
                  <div className='head_box'>
                    <img alt='' src={item.avatar} className='head' />
                    <div className='cen'>
                      <p className='name'>{item.nickname}</p>
                      <p className='time'>{item.time}</p>
                    </div>
                    <div
                      className='hua_btn'
                      onClick={this.xh.bind(this, item.id, item.is_self)}
                    >
                      <img
                        alt=''
                        src={require("../../imgs/999.png")}
                        className='hua'
                      />
                      <p className='xh'>打赏</p>
                    </div>
                  </div>
                  <div className='txt_box'>
                    <div
                      onClick={() => {
                        this.props.history.push(
                          "/page/home/square/squaredetail/" + item.id
                        );
                      }}
                    >
                      {item.type == 4 ? (
                        <p className='desc1'>
                          第{item.is_nun}期 PK赛：
                          <br />
                          {item.content}
                        </p>
                      ) : (
                        <p className='desc1'>{item.content}</p>
                      )}
                      {/* <p className='desc1'>{item.content}</p> */}

                      {item.imgs.length > 0 && (
                        <div className='img_btn'>
                          {item.type == 1 && (
                            <img
                              alt=''
                              src={item.imgs[0]}
                              style={{
                                maxWidth: "100%",
                                maxHeight: "35vh",
                                width: "auto",
                                borderRadius: "5px",
                              }}
                            />
                          )}
                          {item.type == 2 && item.imgs[0].indexOf(".amr") && (
                            <div key={"img" + index}>
                              <button
                                onClick={
                                  this.state.iconFlag
                                    ? this.paused.bind(this)
                                    : this.playVoice.bind(this, item)
                                }
                                style={{
                                  border: "none",
                                  width: "10vw",
                                  backgroundColor: "#ccc",
                                  color: "#fff",
                                  borderRadius: "10px",
                                  height: "5vw",
                                  marginBottom: 10,
                                }}
                              >
                                {this.state.iconFlag ? "暂停" : "播放"}
                              </button>
                            </div>
                          )}
                          {item.type == 2 && !item.imgs[0].indexOf(".amr") && (
                            <audio autoplay controls src={item.imgs[0]}></audio>
                          )}
                          {item.type == 3 && (
                            <video
                              controls
                              poster={ item.imgs[0] + '?vframe/jpg/offset/1' }
                              
                              src={item.imgs[0]}
                              style={{
                                maxWidth: "100%",
                                maxHeight: "35vh",
                                width: "auto",
                                borderRadius: "5px",
                              }}
                            ></video>
                          )}
                          {item.type == 4 && (
                            <video
                              controls
                              poster={ item.imgs[0] + '?vframe/jpg/offset/1' }
                            
                              autoPlay="autoPlay"
                              src={item.imgs[0]}
                              style={{
                                maxWidth: "100%",
                                maxHeight: "35vh",
                                width: "auto",
                                borderRadius: "5px",
                              }}
                            ></video>
                          )}
                          {item.type == 1 && (
                            <p
                              className='go_photo'
                              onClick={(event) => {
                                event.stopPropagation();
                                this.setState({
                                  show: true,
                                  imglist: item.imgs,
                                });
                              }}
                            >
                              <img
                                alt=''
                                src={require("../../imgs/photo.png")}
                              />
                              <span>共{item.imgs.length}张</span>
                            </p>
                          )}
                        </div>
                      )}
                    </div>
                    <div className='btnbox'>
                      <div
                        className='zan'
                        onClick={this.zan.bind(this, item.id, index)}
                      >
                        {item.is_zan === 1 ? (
                          <img alt='' src={require("../../imgs/zan2.png")} />
                        ) : (
                          <img alt='' src={require("../../imgs/zan1.png")} />
                        )}
                        <p>{item.zan_num}</p>
                      </div>
                      <div
                        className='edit'
                        onClick={() => {
                          this.props.history.push(
                            "/page/home/square/sendcomment/" + item.id
                          );
                        }}
                      >
                        <img alt='' src={require("../../imgs/edit.png")} />
                        <p>{item.comment_num}</p>
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </ReactPullLoad>
        {/* <div className='sq_list'>
					<div className='item'>
						<div className='head_box'>
							<img alt='' src={require('../../imgs/head.png')} className='head' />
							<div className='cen'>
								<p className='name'>小白白</p>
								<p className='time'>15小时前·小白</p>
							</div>
							<div className='hua_btn' onClick={this.xh.bind(this)}>
								<img alt='' src={require('../../imgs/hua.png')} className='hua' />
								<p className='xh'>献花</p>
							</div>
						</div>
						<div className='txt_box'>
							<div onClick={(e)=>{
								if(e.target === findDOMNode(this.refs.imglist)||e.target === findDOMNode(this.refs.img)||e.target === findDOMNode(this.refs.span)){
									return;
								}
								this.props.history.push('/page/home/square/squaredetail')
							}}>
								<p className='desc1'>我喜欢这个视频，希望老师可以多发些这个类型的课程，给我带来了非常大的启发，关注老师了。可以学习到很多新的情感处理方法。</p>
								<div className='img_btn'>
									<img alt='' src={require('../../imgs/banner.png')} />
									<p ref='imglist' className='go_photo' onClick={()=>{
										this.setState({
											show: true,
										})
									}}>
										<img ref='img' alt='' src={require('../../imgs/photo.png')} />
										<span ref='span'>共5张</span>
									</p>
								</div>
							</div>
							<div className='btnbox'>
								<div className='zan'>
									<img alt='' src={require('../../imgs/zan1.png')} />
									<p>127</p>
								</div>
								<div className='edit' onClick={()=>{this.props.history.push('/page/home/square/sendcomment')}}>
									<img alt='' src={require('../../imgs/edit.png')} />
									<p>17</p>
								</div>
							</div>
						</div>
					</div>
				</div> */}
        {/* 查看大图 */}
        <div
          className={`mask ${this.state.show ? "active" : ""}`}
          onClick={() => {
            this.setState({
              show: false,
              slideIndex: 1,
              imglist: [],
            });
          }}
        >
          <Carousel
            autoplay={false}
            className='banner'
            dots={false}
            speed={200}
            beforeChange={(from, to) => {
              this.setState({
                slideIndex: to + 1,
              });
            }}
          >
            {this.state.imglist.map((val, index) => (
              <img key={"banner" + index} alt='' src={val} className='img' />
            ))}
          </Carousel>
          <p className='page'>
            {this.state.slideIndex}/{this.state.imglist.length}
          </p>
          {/* <img alt='' src={require('../../imgs/close.png')} className='close' /> */}
        </div>
      </div>
    );
  }
}
